import android.view.View

/**
 * @author       CT
 * @date         2024/3/7
 * @description  View 扩展
 *
 */

/**
 * View Click 扩展
 * @receiver T
 * @param block Function1<T, Unit>
 */
fun <T : View> T.click(block: (T) -> Unit) {
  setOnClickListener {
    block(this)
  }
}


/**
 * 扩展点击事件，默认 500ms 内不能触发 2 次点击
 * @receiver T
 * @param time Long
 * @param block Function1<T, Unit>
 */
fun <T : View> T.clickWithDuration(time: Long = 500, block: (T) -> Unit) {
  delayTime = time
  setOnClickListener {
    if (canClick()) {
      block(this)
    }
  }
}


/**
 * 私有扩展属性，允许2次点击的间隔时间
 */
private var <T : View> T.delayTime: Long
  get() = getTag(0x7FFF0001) as? Long ?: 0
  set(value) {
    setTag(0x7FFF0001, value)
  }

/**
 * 私有扩展属性，记录点击时的时间戳
 */
private var <T : View> T.lastClickTime: Long
  get() = getTag(0x7FFF0002) as? Long ?: 0
  set(value) {
    setTag(0x7FFF0002, value)
  }

/**
 * 私有扩展方法，判断能否触发点击事件
 * @receiver T
 * @return Boolean
 */
private fun <T : View> T.canClick(): Boolean {
  var flag = false
  val now = System.currentTimeMillis()
  if (now - this.lastClickTime >= this.delayTime) {
    flag = true
    this.lastClickTime = now
  }
  return flag
}


